package com.fingard.dsp.bank.directbank.pab01;

import java.io.BufferedReader;
import java.io.File;
import java.io.StringReader;
import java.util.Calendar;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.IQryRefund;
import com.fingard.dsp.bank.reqrespobj.qryrefund.ReqQryRefund;
import com.fingard.dsp.bank.reqrespobj.qryrefund.RetAtsQryRefund;
import com.fingard.dsp.bank.reqrespobj.qryrefund.detail.RetAtsRefundDetail;
import com.fingard.io.FileHelper;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

/**
 * 平安银行银企直联退票查询
 * 
 * 开发依据:
 * 1、接口文档:平安银行银企直连-跨行快付接口V0.7.docx
 * 2、接口清单:
 * 		1. 3.5 对账/差错文件查询[KHKF05]
 * @author Cruise
 *
 */
public class PAB01QryRefund extends PAB01Base implements IQryRefund {
	@Override
	public RetAtsQryRefund d_qry_refund(ReqQryRefund p_req) throws Exception {
		RetAtsQryRefund retAts = new RetAtsQryRefund(p_req.reqHeader);
        retAts.writeStart();

        String tmpRespCode = "";
        String tmpRespInfo = "";
        
        int tmpSuccCount = 0;
        double tmpTotalAmt = 0;

        try {
        	Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_req.getQryStartDate());

            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_req.getQryEndDate());
            tmpCalendarTo.add(Calendar.DAY_OF_MONTH, 1);
            
            while (tmpCalendarFrom.compareTo(tmpCalendarTo) == -1) {
            	PAB01Header bankHeader = new PAB01Header();
    			bankHeader.trncode = "KHKF05";
    			bankHeader.fourZero = "0000";
    			bankHeader.reqSeqNo = getQryTransID();

    			XmlTextWriter xmlWriter = new XmlTextWriter();
    			xmlWriter.autoFormat = false;
    			xmlWriter.writeStartDocByDeclaration("<?xml version=\"1.0\" encoding=\"" + getCharset() + "\"?>");
    			xmlWriter.writeStartElement("Result");
    			xmlWriter.writeElementString("Date", Format.Date8Format.format(tmpCalendarFrom.getTime()));
    			xmlWriter.writeElementString("AcctNo", p_req.payAct);
    			xmlWriter.writeElementString("FileType","KHKF02");
    			xmlWriter.writeElementClosed("BatchNo");
    			xmlWriter.writeEndDocument();

    			String[] tmpStrRet = sendToBank(xmlWriter.toXmlString(), bankHeader);

    			if (tmpStrRet[0].length() == 0) {
    				byte[] retBytes = tmpStrRet[1].getBytes(getCharset());
    				String tmpRetCode = new String(retBytes, 87, 6, getCharset());
    				String tmpRetMsg = new String(retBytes, 93, 100, getCharset()).trim();
    				tmpRetMsg = StringHelper.trimStart(tmpRetMsg, ":");

    				if ("000000".equals(tmpRetCode)) {
    					StringBuilder tmpSbMsg = new StringBuilder();
    					XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1].substring(tmpStrRet[1].indexOf("<")), tmpSbMsg);
    					if (tmpBkReader != null) {
							String qryState = tmpBkReader.getFirstText("/Result/Stt");
							if ("20".equals(qryState)) {
								while(tmpBkReader.read("/Result/list")) {
									bankHeader = new PAB01Header();
					    			bankHeader.trncode = "FILE03";
					    			bankHeader.fourZero = "0000";
					    			bankHeader.reqSeqNo = getQryTransID();

					    			xmlWriter = new XmlTextWriter();
					    			xmlWriter.autoFormat = false;
					    			xmlWriter.writeStartDocByDeclaration("<?xml version=\"1.0\" encoding=\"" + getCharset() + "\"?>");
					    			xmlWriter.writeStartElement("Result");
					    			xmlWriter.writeElementString("TradeSn", p_req.reqHeader.transSeqID);
					    			String fileName = tmpBkReader.readedXElement.getSingleText("FileName");
					    			xmlWriter.writeElementString("FileName", fileName);
					    			xmlWriter.writeElementClosed("FilePath");
					    			xmlWriter.writeElementString("RandomPwd", tmpBkReader.readedXElement.getSingleText("RandomPwd"));
					    			xmlWriter.writeElementString("SignData", "");
					    			xmlWriter.writeElementString("HashData", "");
					    			xmlWriter.writeEndDocument();

					    			tmpStrRet = sendToBank(xmlWriter.toXmlString(), bankHeader);
					    			
					    			if (tmpStrRet[0].length() == 0) {
										retBytes = tmpStrRet[1].getBytes(getCharset());
										tmpRetCode = new String(retBytes, 87, 6, getCharset()).trim();
										tmpRetMsg = new String(retBytes, 94, 99, getCharset()).trim();
										if ("000000".equals(tmpRetCode)) {
											String ftpLocalDir = getBankConfig().getValueAsString("ftpLocalDir");
											if (StringHelper.isNullOrEmpty(ftpLocalDir)) {
												tmpRespCode = "-1";
												tmpRespInfo = "配置文件缺失'ftpLocalDir'节点配置";
												retAts.writeRespCode(tmpRespCode);
												retAts.writeRespInfo(tmpRespInfo);
												retAts.writeEnd();
												return retAts;
											}

											String localFilePath = StringHelper.trimEnd(ftpLocalDir, File.separator) + File.separator + fileName;
											WriteBankLogLn2("本地结果文件路径:" + localFilePath);

											if (!new File(localFilePath).exists()) {
												tmpRespCode = "-1";
												tmpRespInfo = "本地文件不存在";
												continue;
											}

											String tmpRetStr = FileHelper.readFileText(localFilePath, getCharset());
											WriteBankLogLn2("当前文件内容:\r\n" + tmpRetStr);

											StringReader strReader = new StringReader(tmpRetStr);
											BufferedReader tmpReader = new BufferedReader(strReader);

											String line = tmpReader.readLine();
											String[] headerValues = line.split("\\|\\:\\:\\|");
											tmpSuccCount += Integer.parseInt(headerValues[1]);
											tmpTotalAmt += Double.parseDouble(headerValues[2]);

											while(true) {
												String eachline = tmpReader.readLine();
												if(eachline == null){
													break;
												}

												String[] eachNodes = eachline.split("\\|\\:\\:\\|");

												RetAtsRefundDetail tmpRetDetail = new RetAtsRefundDetail();

												tmpRetDetail.askNum = eachNodes[7];
												tmpRetDetail.recAct = eachNodes[2];
												tmpRetDetail.recActName = eachNodes[3];
												tmpRetDetail.amount = eachNodes[5];
												tmpRetDetail.refundTicketDate = Format.Date10Format.format(Format.Date8Format.parse(eachNodes[0]));
												tmpRetDetail.submitTime = Format.DateTimeFormat.format(Format.Date8Format.parse(eachNodes[1]));
												tmpRetDetail.refundTicketReason = eachNodes[11];
												tmpRetDetail.strAbstract = eachNodes[10];
												tmpRetDetail.memo = eachNodes[11];

												retAts.writeRetDetail(tmpRetDetail);
											}
										} else {
											tmpRespCode = "-1";
						                    tmpRespInfo = tmpRetMsg;
										}
									} else {
										tmpRespCode = "-1";
						                tmpRespInfo = tmpStrRet[1];
									}
								}
							} else {
								tmpRespCode = "-1";
			                    tmpRespInfo = "本日无记录";
							}
	    				} else {
	    					tmpRespCode = "-1";
		                    tmpRespInfo = tmpSbMsg.toString();
	    				}
	    			} else {
	    				tmpRespCode = "-1";
	                    tmpRespInfo = tmpRetMsg;
	    			}
	            } else {
	            	tmpRespCode = "-1";
	                tmpRespInfo = tmpStrRet[1];
	            }
    			
    			tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
            }
            
            retAts.totleAmount = String.valueOf(tmpTotalAmt);
            retAts.totleNum = String.valueOf(tmpSuccCount);
        } catch (Exception ex) {
        	ex.printStackTrace();
            tmpRespCode = "-1";
            tmpRespInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }

        if (tmpRespCode.equals("-1")) {
            retAts.writeRespCode(tmpRespCode);
            retAts.writeRespInfo(tmpRespInfo);
        } else if (retAts.getWrittenRdCount() == 0) {
            retAts.writeRespCode("0");
            retAts.writeRespInfo("当前时间范围内无退票数据");
        }

        retAts.writeEnd();
        return retAts;
	}
}
